package com.xbongbong.schedule.producer.impl;

import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.schedule.binders.ScheduleTaskMqProducerBinder;
import com.xbongbong.schedule.domain.entity.ScheduleTaskEntity;
import com.xbongbong.schedule.pojo.dto.ScheduleTaskRabbitmqDTO;
import com.xbongbong.schedule.producer.ScheduleTaskProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("scheduleTaskProducer")
@EnableBinding({ScheduleTaskMqProducerBinder.class})
public class ScheduleTaskProducerImpl implements ScheduleTaskProducer {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTaskProducer.class);

    @Resource
    private ScheduleTaskMqProducerBinder scheduleMqProducerBinder;

    @Override
    public void addScheduleTask(ScheduleTaskRabbitmqDTO scheduleTaskRabbitmqDTO) {
        ScheduleTaskEntity scheduleTask = scheduleTaskRabbitmqDTO.getScheduleTaskEntity();
        long delayTime = (scheduleTask.getTriggerTime() - DateTimeUtil.getInt()) * 1000;
        MessageHeaderAccessor messageHeaderAccessor = new MessageHeaderAccessor();
        messageHeaderAccessor.setHeader("x-delay", delayTime);
        MessageBuilder<ScheduleTaskRabbitmqDTO> messageBuilder = MessageBuilder.withPayload(scheduleTaskRabbitmqDTO).setHeaders(messageHeaderAccessor);
        scheduleMqProducerBinder.scheduleTaskOutput().send(messageBuilder.build());
    }

    @Override
    public void addScheduleTaskImmediately(ScheduleTaskRabbitmqDTO scheduleTaskRabbitmqDTO) {
        MessageHeaderAccessor messageHeaderAccessor = new MessageHeaderAccessor();
        MessageBuilder<ScheduleTaskRabbitmqDTO> messageBuilder = MessageBuilder.withPayload(scheduleTaskRabbitmqDTO).setHeaders(messageHeaderAccessor);
        scheduleMqProducerBinder.scheduleTaskImmediatelyOutput().send(messageBuilder.build());
    }
}
